<template>
  <div>
    <el-space wrap :fill="true" style="width:100%">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <strong>商品(Spu)介绍</strong>
          </div>
        </template>
        <!-- 表单 -->
        <el-form
          ref="introDuceRef"
          :model="formData"
          :rules="rule"
          label-width="110px"
          class="demo-formData"
        >
          <el-form-item label="商品名称" prop="title">
            <el-input v-model="formData.title" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="原始价格" prop="originalPrice">
            <el-input placeholder="请输入原始价格" v-model="formData.originalPrice">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="当前价格" prop="price">
            <el-input placeholder="请输入当前价格" v-model="formData.price">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="VIP价格" prop="vipPrice">
            <el-input placeholder="请输入VIP价格" v-model="formData.vipPrice">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="剩余库存" prop="inventory">
            <el-input v-model="formData.inventory" :disabled="true" placeholder="0"/>
          </el-form-item>
          <el-form-item label="运费模板" prop="freightTemplateId">
            <el-select class="m-2" placeholder="请选择运费模板" v-model="formData.freightTemplateId">
              <el-option
                v-for="item in freightTemplate"
                :label="item.title"
                :value="item.id"
                :key="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否在售" prop="status" required>
            <el-radio :label="1" v-model="formData.status">在售</el-radio>
            <el-radio :label="0" v-model="formData.status">下架</el-radio>
          </el-form-item>
          <el-form-item label="商品图片" prop="img">
            <el-upload
              :action="list"
              list-type="picture-card"
              :on-success="handleAvatarSuccess"
              :on-remove="handleRemove"
              :headers="token"
              ref="imgs"
            >
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品单位" prop="unit">
            <el-input v-model="formData.unit" placeholder="请输入商品单位" />
          </el-form-item>
          <el-form-item label="所属类目" prop="categoryId">
            <el-cascader
              :options="options"
              :props="props"
              v-model="formData.categoryId"
              placeholder="请选择所属类目"
            />
          </el-form-item>
          <el-form-item label="商品简介" prop="description">
            <el-input v-model="formData.description" placeholder="请输入商品简介" />
          </el-form-item>
          <el-form-item label="商品详细介绍" prop="detail">
            <TinyMce ref="editor" v-model="formData.detail" />
          </el-form-item>
        </el-form>
      </el-card>
      <!-- 商品参数 -->
      <el-card class="box-card">
        <div class="card-header">
          <strong>商品参数</strong>
          <el-button type="primary" plain @click="addCommodity" style="margin:20px;">添加</el-button>
        </div>
        <el-table :data="formData.attributeList">
          <el-table-column prop="attribute" label="商品参数名称" />
          <el-table-column prop="value" label="商品参数值" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 规格维度 -->
      <el-card class="box-card" style="with:100%">
        <div class="card-header">
          <strong>规格维度</strong>
          <el-button type="primary" plain @click="addSpecification" style="margin:20px;">添加</el-button>
        </div>
        <el-table :data="formData.specificationList">
          <el-table-column label="维度id" />
          <el-table-column prop="title" label="维度名称" />
          <el-table-column prop="gmtCreate" label="创建时间">
            <template #default="scope">{{ new Date(scope.row.gmtCreate).followTime() }}</template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" @click="amendSpecificationList(scope.row,scope.$index)">修改</el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteSpecificationList(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 商品sku详情 -->
      <el-card class="box-card" style="with:100%;">
        <template #header>
          <div class="card-header">
            <strong>商品(Sku)详情</strong>
            <el-button type="primary" plain @click="batchPricings" style="margin:20px;">批量定价</el-button>
          </div>
        </template>
        <div class="tab">
          <div
            v-for="(item, index) in formData.specificationList"
            :key="index"
            style="margin-bottom: 5px"
          >
            <el-tag class="ml-2" type="warning" style="margin-right: 10px">
              {{
              item.title
              }}
            </el-tag>
            <el-tag
              v-for="(tag, indexs) in item.values"
              :key="indexs"
              closable
              style="margin-right: 5px"
              :disable-transitions="false"
              @close="deleteTag(indexs, index)"
            >{{ tag }}</el-tag>
            <el-input
              v-if="item.inputSkuTagVisible"
              :key="index"
              ref="InputRef"
              style="width: 100px"
              v-model="item.inputSkuTagValue"
              @keyup.enter="addTag(index)"
              @blur="addTag(index)"
            />
            <el-button
              v-else
              class="button-new-tag ml-1"
              size="small"
              @click="showInput(index)"
            >+ 添加</el-button>
          </div>
        </div>
        <el-table :data="formData.skuList" border>
          <el-table-column
            :label="item.title"
            :prop="'id_' + item.title"
            align="center"
            v-for="item in formData.specificationList"
            :key="item"
            width="100"
          />
          <el-table-column prop="stock" label="SkuId" align="center" width="100"/>
          <el-table-column prop="price" label="￥价格(元)" align="center" width="200">
            <template #default="scope">
              <el-input-number v-model="scope.row.price" :min="1" />
            </template>
          </el-table-column>
          <el-table-column prop="vipPrice" label="￥VIP价(元)" align="center" width="200">
            <template #default="scope">
              <el-input-number v-model="scope.row.vipPrice" :min="1" />
            </template>
          </el-table-column>
          <el-table-column prop="originalPrice" label="￥吊牌价(元)" align="center" width="200">
            <template #default="scope">
              <el-input-number v-model="scope.row.originalPrice" :min="1"/>
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存(件)" align="center" width="200">
            <template #default="scope">
              <el-input-number v-model="scope.row.stock" :min="1" />
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量(克)" align="center" width="200">
            <template #default="scope">
              <el-input-number v-model="scope.row.weight" :min="1" />
            </template>
          </el-table-column>
          <el-table-column prop="img" label="SKU图片" align="center">
            <template #default="scope">
              <el-upload
                :action="list"
                :on-success="handleAvatarSuccess1"
                :headers="token"
                class="avatar-uploader"
                :show-file-list="false"
              >
                <img
                  v-if="scope.row.img"
                  :src="scope.row.img"
                  class="avatar"
                  style="width:50px;height:50px"
                  @click="index = scope.$index"
                />
                <el-icon class="avatar-uploader-icon" v-else style="width:50px;height:50px" @click="index = scope.$index">
                  <Plus />
                </el-icon>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column prop="barCode" label="条形码" align="center" width="200">
            <template #default="scope">
              <el-input v-model="scope.row.barCode" placeholder="随机生成条形码" class="input-with-select">
                <template #append>
                  <el-button @click="scope.row.barCode = +new Date()">随机</el-button>
                </template>
              </el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <div class="btn">
        <el-button @click="closes">取消</el-button>
        <el-button type="primary" @click="addiTion">保存商品</el-button>
      </div>
    </el-space>
    <!-- 对话框 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%" :before-close="handleClose">
      <!-- 商品参数 -->
      <el-form
        @submit.prevent
        ref="parameterRef"
        :model="parameterForm"
        :rules="parameterRules"
        label-width="110px"
        class="demo-ruleForm"
        v-if="title=='设置商品参数'"
      >
        <el-form-item label="商品参数名称" prop="attribute">
          <el-input v-model="parameterForm.attribute" />
        </el-form-item>
        <el-form-item label="商品参数值" prop="value">
          <el-input v-model="parameterForm.value" />
        </el-form-item>
      </el-form>
      <!-- 规格 -->
      <el-form
        @submit.prevent
        ref="specificationRef"
        :rules="specificationRules"
        label-width="110px"
        :model="specificationForm"
        class="demo-ruleForm"
        v-if="title=='创建规格'"
      >
        <el-form-item label="类型名称" prop="title">
          <el-input v-model="specificationForm.title" />
        </el-form-item>
      </el-form>
      <!-- 修改规格 -->
      <el-form
        @submit.prevent
        ref="specificationRef"
        :rules="specificationRules"
        label-width="110px"
        :model="specificationForm"
        class="demo-ruleForm"
        v-if="title=='修改规格'"
      >
        <el-form-item label="类型名称" prop="title">
          <el-input v-model="specificationForm.title" />
        </el-form-item>
      </el-form>
      <!-- 批量定价 -->
      <el-form
        @submit.prevent
        :model="particularsForm"
        label-width="110px"
        class="demo-ruleForm"
        v-if="title=='批量定价'"
      >
        <el-form-item label="现价(￥)" prop="price">
          <el-input-number v-model="particularsForm.price" :min="1" />
        </el-form-item>
        <el-form-item label="VIP价格(￥)" prop="vipPrice">
          <el-input-number v-model="particularsForm.vipPrice" :min="1"/>
        </el-form-item>
        <el-form-item label="吊牌价(￥)" prop="originalPrice">
          <el-input-number v-model="particularsForm.originalPrice" :min="1"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            v-if="title=='设置商品参数'"
            @click="confirmAddParameter('parameterRef')"
          >确定</el-button>
          <el-button
            type="primary"
            v-if="title=='创建规格'"
            @click="confirmAddSpecification('specificationRef')"
          >确定</el-button>
          <el-button
            type="primary"
            v-if="title=='修改规格'"
            @click="confirmSpecificationList('specificationRef')"
          >确定</el-button>
          <el-button type="primary" v-if="title=='批量定价'" @click="confirmAddPricing">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Plus } from "@element-plus/icons-vue";
import { post, get, host } from "@/utlis/http";
import Cookies from "js-cookie";
import TinyMce from "@/components/TinyMce.vue"; //富文本
import { mapActions } from "vuex";
import store from "@/store";
export default {
  components: {
    Plus,
    TinyMce,
  },
  setup() {
    return {
      Plus,
    };
  },
  data() {
    return {
      formData: {
        //表单
        title: "", //商品名称
        originalPrice: 0, //原始价格
        price: 0, //当前价格
        vipPrice: 0, //vip价格
        inventory: "", //剩余库存
        status: 1, //是否在售
        img: "", //商品图片
        imgList: [], //商品总图
        unit: "", //商品单位
        freightTemplateId: "", //运费模板
        categoryId: "", //所属类目
        description: "", //商品简介
        detail: "", //商品详细介绍
        skuList: [], //商品SKU详情
        specificationList: [], //规格维度
        attributeList: [], //商品参数
      },
      index: 0, //上传图片的下标
      list:host+'/upload/admin',
      freightTemplate: [], //运费模板
      options: [], //所属类目
      props: {
        value: "id", //指定选项的值为选项对象的某个属性值
        label: "title", //指定选项标签为选项对象的某个属性值
        children: "childrenList", //指定选项的子选项为选项对象的某个属性值
        emitPath: false, //在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
      },
      rule: {
        title: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        originalPrice: [
          { required: true, message: "请输入原始价格", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入当前价格", trigger: "blur" }],
        vipPrice: [
          { required: true, message: "请输入VIP价格", trigger: "blur" },
        ],
        unit: [{ required: true, message: "请输入商品单位", trigger: "blur" }],
        detail: [
          { required: true, message: "请输入商品详细介绍", trigger: "blur" },
        ],
      },
      //商品参数正则
      parameterRules: {
        attribute: [
          { required: true, message: "请输入商品参数名称", trigger: "blur" },
        ],
        value: [
          { required: true, message: "请输入商品参数值", trigger: "blur" },
        ],
      },
      //规格正则
      specificationRules: {
        title: [{ required: true, message: "请输入类型名称", trigger: "blur" }],
      },
      dialogVisible: false, //商品参数对话框
      title: "设置商品参数", //判断是设置商品参数还是规格维度或批量定价
      parameterForm: {
        //商品参数表单
        attribute: "", //商品参数名称
        value: "", //商品参数值
      },
      particularsForm: {
        //批量定价表单
        originalPrice: 0, //吊牌价
        price: 0, //现价
        vipPrice: 0, //vip价格
      },
      specificationForm: {
        title: "",
      }, //规格参数表单
      dialogVisibles: false, //预览图片
    };
  },
  computed: {
    token() {
      let headers = { AdminToken: Cookies.get("token") };
      return headers;
    },
  },
  created() {
    this.categoryTree();
    this.freightTemplates();
  },
  methods: {
    ...mapActions["closeTag"],
    //添加
    addiTion() {
      this.$refs.introDuceRef.validate((val) => {
        if (!val) {
          ElMessage.warning("商品(Spu)介绍不能为空");
          return;
        }
      });
      let data = {
        _gp: "admin.product",
        _mt: "create",
        spuDTO: JSON.stringify(this.formData),
      };
      post(data).then((res) => {
        let { errno, errmsg } = res.data;
        if (200 == errno) {
          ElMessageBox.confirm("是否继续添加?", "创建成功", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "提示",
          })
            .then(() => {
              this.inits(this.formData)
              this.$refs.introDuceRef?.resetFields();
              this.$refs.imgs?.clearFiles();
              this.formData.specificationList = []
              this.formData.attributeList = []
              this.formData.skuList = []
            })
            .catch(() => {
              ElMessage.success("添加成功")
              this.$refs.introDuceRef?.resetFields();
              this.$refs.imgs?.clearFiles();
              this.formData.specificationList = []
              this.formData.attributeList = []
              this.formData.skuList = []
              store.dispatch("closeTag", this.$route.name);
            });
        } else {
          ElMessage.warning(errmsg);
        }
      });
    },
    //添加商品参数formData
    addCommodity() {
      this.parameterForm.attribute = "";
      this.parameterForm.value = "";
      this.title = "设置商品参数";
      this.dialogVisible = true;
    },
    // 确定添加商品参数
    confirmAddParameter(parameterRef) {
      this.$refs[parameterRef].validate((valid) => {
        if (valid == false) {
          return;
        } else {
          let bool = this.formData.attributeList.find(//查找
            (item) => item.attribute == this.parameterForm.attribute
          );
          if (!bool) {
            this.formData.attributeList.push({ ...this.parameterForm });
            this.dialogVisible = false;
            this.inits(this.parameterForm);
          }else {
            ElMessage.warning("该参数已存在");
          }
        }
      });
    },
    //删除添加商品参数
    handleDelete(index) {
      this.formData.attributeList.splice(index, 1);
    },
    //添加规格维度
    addSpecification() {
      this.specificationForm.title = "";
      this.title = "创建规格";
      this.dialogVisible = true;
    },
    // 确定添加规格维度
    confirmAddSpecification(specificationRef) {
      this.$refs[specificationRef].validate((valid) => {
        if (valid == false) {
          return;
        } else {
          let find = this.formData.specificationList.find(
            (item) => item.title == this.specificationForm.title
          );
          if (!find) {
            this.formData.specificationList.push({
              title: this.specificationForm.title,
              values: [],
              inputSkuTagVisible: false,
              gmtCreate: +new Date(),
              inputSkuTagValue: "",
            });
            this.dialogVisible = false;
          } else {
            ElMessage.warning("该规格名称已存在");
          }
        }
      });
    },
    // 修改规格维度
    amendSpecificationList(row, index) {
      this.index = index;
      this.title = "修改规格";
      this.dialogVisible = true;
      Object.assign(this.specificationForm, row);
    },
    //确定保存编辑规格维度
    confirmSpecificationList(specificationRef) {
      this.$refs[specificationRef].validate((valid) => {
        if (valid == false) {
          return;
        } else {
          this.formData.specificationList.splice(this.index, 1, {
            title: this.specificationForm.title,
            values: [],
            inputSkuTagVisible: false,
            gmtCreate: +new Date(),
            inputSkuTagValue: "",
          });
          this.dialogVisible = false;
        }
      });
    },
    //删除规格维度
    deleteSpecificationList(index) {
      this.formData.specificationList.splice(index, 1);
    },
    //批量定价
    batchPricings() {
      this.title = "批量定价";
      this.dialogVisible = true;
    },
    // 确定添加批量定价
    confirmAddPricing() {
      let { price, vipPrice, originalPrice } = this.particularsForm;
      this.formData.skuList.forEach((item) => {
        item.price = price;
        item.originalPrice = originalPrice;
        item.vipPrice = vipPrice;
      });
      this.dialogVisible = false;
    },
    // 标签页显示输入框
    showInput(index) {
      this.formData.specificationList[index].inputSkuTagVisible = true;
      this.$nextTick(() => {
        this.$refs.InputRef[0]?.focus();//调用失去焦点事件
      });
    },
    // 删除标签页
    deleteTag(ind, index) {
      this.formData.specificationList[index].values.splice(ind, 1);
      this.tableList();
    },
    // 添加标签页
    addTag(index) {
      if (this.formData.specificationList[index].inputSkuTagValue) {
        this.formData.specificationList[index].values.push(
          this.formData.specificationList[index].inputSkuTagValue
        );
      }
      this.formData.specificationList[index].inputSkuTagVisible = false;
      this.formData.specificationList[index].inputSkuTagValue = "";
      this.tableList();
    },
    tableList() {
      const specList = this.formData.specificationList;
      const valueList = specList.map((item) => item.values);
      const titles = specList.map((item) => item.title);
      //根据属性值，生成笛卡尔直积数据
      var skuList = valueList.reduce(
        (pre, next) => {
          var array = [];
          pre.forEach((item1) => {
            next.forEach((item2) => {
              array.push(item1.concat([item2]));
            });
          });
          return array;
        },
        [[]]
      );
      const { price, vipPrice, originalPrice } = this.particularsForm;
      //构建sku表格数据
      var shuTable = skuList.map((item) => {
        let obj = {
          price: price, //现价
          vipPrice: vipPrice, //VIP价
          originalPrice: originalPrice, //吊牌价
          stock: 0, //库存
          barCode: "", //条形码
          weight: 1, //重量
          img: "", //sku图片
          title: [], //规格维度的所有标题
          specification: [], //规格维度
        };
        item.forEach((val, index) => {
          var key = "id_" + titles[index];
          obj[key] = val;
          obj.title.push(val);
          obj.specification.push(titles[index] + "_" + val);
        });
        obj.title = obj.title.join(",");
        obj.specification = obj.specification.join(",");
        return obj;
      });
      this.formData.skuList = shuTable;
    },
    //运费模板
    freightTemplates() {
      let data = {
        _gp: "admin.freight",
        _mt: "list",
      };
      get(data).then((res) => {
        let { data, errno } = res.data;
        if (200 == errno) {
          this.freightTemplate = data;
        }
      });
    },
    //所属类目
    categoryTree() {
      let data = {
        _gp: "admin.category",
        _mt: "categoryTree",
      };
      post(data).then((res) => {
        let { data, errno } = res.data;
        if (200 == errno) {
          this.options = data;
        }
      });
    },
    //取消
    closes() {
      ElMessageBox.confirm("确定关闭吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "提示",
      })
        .then(() => {
          store.dispatch("closeTag", this.$route.name);
          ElMessage.success("关闭成功");
        })
        .catch(() => {
          ElMessage.info("取消关闭");
        });
    },
    //上传图片
    handleAvatarSuccess(file) {
      let { url, errno } = file;  
      if (200 == errno) {
        this.formData.imgList.push(url);
        this.formData.img = this.formData.imgList[0]
      }
    },
    //图片移除
    handleRemove(uploadFile, uploadFiles){
      let index = this.formData.imgList.findIndex(
        (item) => uploadFile.url == item
      );
      this.formData.imgList.splice(index, 1);
    },
    handleAvatarSuccess1(file) {
      let { errno, url } = file;
      if (200 == errno) {
        this.formData.skuList[this.index].img = url;
      }
    },
    // 关闭商品参数的对话框
    handleClose(done) {
      ElMessageBox.confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
  },
};
</script>

<style lang="less" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.btn {
  text-align: right;
}
</style>